﻿using System;
using System.Windows;
using System.Windows.Media.Animation;

namespace Quebec.Silverlight.Animations
{
    public class PositionAnimation : AnimationBase
    {
        public static TimeSpan DefaultDuration = TimeSpan.FromMilliseconds(250);

        public PositionAnimation(double left, double top)
            : this(left, top, DefaultDuration)
        {
        }

        public PositionAnimation(double left, double top, TimeSpan duration)
        {
            Left = left;
            Top = top;
            Duration = duration;
        }

        public double Left
        {
            get;
            private set;
        }

        public double Top
        {
            get;
            private set;
        }

        public TimeSpan Duration
        {
            get;
            private set;
        }

        protected override void ApplyValues(Storyboard storyboard)
        {
            if (storyboard == null)
                throw new ArgumentNullException("storyboard");

            var leftAnimation = storyboard.Children[0] as DoubleAnimationUsingKeyFrames;
            var topAnimation = storyboard.Children[1] as DoubleAnimationUsingKeyFrames;

            leftAnimation.KeyFrames[0].Value = Left;
            leftAnimation.KeyFrames[0].KeyTime = KeyTime.FromTimeSpan(Duration);
            topAnimation.KeyFrames[0].Value = Top;
            topAnimation.KeyFrames[0].KeyTime = KeyTime.FromTimeSpan(Duration);
        }

        protected override Storyboard CreateStoryboard()
        {
            var storyboard = new Storyboard();

            var leftAnimation = new DoubleAnimationUsingKeyFrames();
            var topAnimation = new DoubleAnimationUsingKeyFrames();

            Storyboard.SetTargetProperty(leftAnimation, new PropertyPath("(UIElement.RenderTransform).(CompositeTransform.TranslateX)"));
            Storyboard.SetTargetProperty(topAnimation, new PropertyPath("(UIElement.RenderTransform).(CompositeTransform.TranslateY)"));

            storyboard.Children.Add(leftAnimation);
            storyboard.Children.Add(topAnimation);

            leftAnimation.KeyFrames.Add(new SplineDoubleKeyFrame()
            {
                KeySpline = new KeySpline()
                {
                    ControlPoint1 = new Point(0.528, 0),
                    ControlPoint2 = new Point(0.142, 0.847)
                }
            });

            topAnimation.KeyFrames.Add(new SplineDoubleKeyFrame()
            {
                KeySpline = new KeySpline()
                {
                    ControlPoint1 = new Point(0.528, 0),
                    ControlPoint2 = new Point(0.142, 0.847)
                }
            });

            return storyboard;
        }
    }
}
